import 'dart:async';
import 'dart:io';

import 'package:baselib/utils/image_util.dart';
import 'package:baselib/utils/navigator_util.dart';
import 'package:cached_network_image/cached_network_image.dart';
import 'package:flutter/material.dart';
import 'package:framelib/utils/drawable_util.dart';
import 'package:framelib/utils/px_util.dart';
import 'package:nim_core/nim_core.dart';
import 'package:photo_view/photo_view.dart';
import 'package:photo_view/photo_view_gallery.dart';
import 'package:yunxin_alog/yunxin_alog.dart';

class PictureViewer extends StatefulWidget {
  const PictureViewer(
      {Key key,  this.messages,  this.showIndex})
      : super(key: key);

  final List<NIMMessage> messages;
  final int showIndex;

  @override
  State<StatefulWidget> createState() => _PictureViewerState();
}

class _PictureViewerState extends State<PictureViewer> {
   StreamSubscription _subscription;
   List<NIMMessage> _galleryItems;
   int _currentIndex;

  void _logI(String content) {
    Alog.i(tag: 'ChatKit', moduleName: 'picture view', content: content);
  }

  PhotoViewGalleryPageOptions _buildItem(BuildContext context, int index) {
    NIMMessage message = _galleryItems[index];
    NIMImageAttachment attachment =
        message.messageAttachment as NIMImageAttachment;
    String path = attachment.path ?? attachment.thumbPath ?? "";
    _logI('build item index:$index ${message.uuid}');
    String url = attachment.url ?? attachment.thumbUrl;
    // ImageProvider imageProvider;
    // if (Platform.isIOS) {
    //   // iOS 不提供下载原图的接口，直接通过url展示
    //   String url = attachment.url ?? attachment.thumbUrl;
    //   _logI('iOS load from url:$url');
    //   imageProvider = CachedNetworkImageProvider(url, cacheKey: url);
    // } else {
    //   if (path != null) {
    //     imageProvider = FileImage(File(path));
    //   } else {
    //     NimCore.instance.messageService
    //         .downloadAttachment(message: message, thumb: false)
    //         .then((value) {
    //       if (value.isSuccess) {
    //         imageProvider = FileImage(File(path));
    //       }
    //     });
    //   }
    // }
    return PhotoViewGalleryPageOptions(
      imageProvider: CachedNetworkImageProvider(url, cacheKey: url),
      initialScale: PhotoViewComputedScale.contained,
      minScale: PhotoViewComputedScale.contained,
      maxScale: PhotoViewComputedScale.contained * 2,
      heroAttributes:
          PhotoViewHeroAttributes(tag: '${message.messageId}${message.uuid}'),
    );
  }

  @override
  void initState() {
    super.initState();
    _subscription =
        NimCore.instance.messageService.onMessageStatus.listen((event) {
      _logI('onMessageStatus ${event.uuid} ${event.attachmentStatus}');
      NIMImageAttachment attachment = event.messageAttachment as NIMImageAttachment;
      String path = attachment.path ?? attachment.thumbPath ?? "";
      if (path != null) {
        int pos = -1;
        for (int i = 0; i < _galleryItems.length; ++i) {
          if (isSameMessage(_galleryItems[i].messageId,_galleryItems[i].uuid,event)) {
            pos = i;
            break;
          }
        }
        if (pos > -1) {
          _galleryItems[pos] = event;
          setState(() {});
          _logI('download finish, update $pos');
        }
      } else {
        NimCore.instance.messageService
            .downloadAttachment(message: event, thumb: false)
            .then((value) {
          if (value.isSuccess) {
            int pos = -1;
            for (int i = 0; i < _galleryItems.length; ++i) {
              if (isSameMessage(_galleryItems[i].messageId,_galleryItems[i].uuid,event))  {
                pos = i;
                break;
              }
            }
            if (pos > -1) {
              _galleryItems[pos] = event;
              setState(() {});
              _logI('download finish, update $pos');
            }
          }
        });
      }
      // if (event.isFileDownload()) {
      //   int pos = -1;
      //   for (int i = 0; i < _galleryItems.length; ++i) {
      //     if (_galleryItems[i].isSameMessage(event)) {
      //       pos = i;
      //       break;
      //     }
      //   }
      //   if (pos > -1) {
      //     _galleryItems[pos] = event;
      //     setState(() {});
      //     _logI('download finish, update $pos');
      //   }
      // }
    });
    _galleryItems = widget.messages;
    _currentIndex = widget.showIndex > 0 ? widget.showIndex : 0;
  }
   bool isSameMessage(String messageId,String uuid,NIMMessage other) {
     if (other != null) {
       if (messageId != null &&
           messageId != '-1' &&
           other.messageId != null &&
           other.messageId != '-1') {
         return messageId == other.messageId;
       } else {
         return uuid == other.uuid;
       }
     }
     return false;
   }
  @override
  void dispose() {
    _subscription.cancel();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Stack(
        children: [
          PhotoViewGallery.builder(
            scrollPhysics: const BouncingScrollPhysics(),
            gaplessPlayback: true,
            reverse: true,
            builder: _buildItem,
            itemCount: _galleryItems.length,
            pageController: PageController(initialPage: _currentIndex),
            onPageChanged: (index) {
              setState(() {
                _currentIndex = index;
              });
            },
          ),
          Positioned(
            right: PxUtil.instance.px_15,
            top: PxUtil.instance.statusBarHeight,
            child: GestureDetector(
              onTap: ()=>NavigatorUtil.goBack(),
              child: ImagesUtil.loadAssetImage(
                  DrawableUtil.instance.icon_room_close,
                  width: PxUtil.instance.px_22
              ),
            )
          )
          // MediaBottomActionOverlay(_galleryItems[_currentIndex]),
        ],
      ),
    );
  }
}
